package dxunderground.winampController.Server.GUI;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JFileChooser;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import dxunderground.winampController.Common.ButtonActionsInterface;
import dxunderground.winampController.Common.GUI;
import dxunderground.winampController.Server.Playlist;
import dxunderground.winampController.Server.PlaylistQueue;

public class ButtonActions implements ButtonActionsInterface {
	private JFileChooser chooser = new JFileChooser();
	private GUI gui;
	private Playlist playlist;
	private Element properties;

	public ButtonActions(GUI gui, Element properties) {
		this.gui = gui;
		this.playlist = new Playlist();
		this.properties = properties;
		this.playlist.startQueue();
	}

	private void browse() {
		chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

		int returnVal = chooser.showOpenDialog(null);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			gui.loadField.setText(file.getAbsolutePath());
		}
	}

	public void load() throws IOException {
		File file = new File(gui.loadField.getText());
		this.saveLoad(gui.loadField.getText());
		playlist.loadPlaylist(file);
		gui.statusLabel.setText(playlist.getSongCount() + "");

		ArrayList<File> songs = playlist.getSongs();
		gui.listModel.clear();
		for (int i = 0; i < songs.size(); i++) {
			gui.listModel.addElement(songs.get(i));
		}
	}

	private void saveLoad(String location) throws IOException {
		if (properties == null) {
			properties = new Element("Prefrences");
		}
		Element previousLoaded = properties.getChild("PreviousLoaded");
		if (previousLoaded == null) {
			previousLoaded = new Element("PreviousLoaded");
			properties.addContent(previousLoaded);
		}
		Element folder = previousLoaded.getChild("Folder");
		if (folder == null) {
			folder = new Element("Folder");
			previousLoaded.addContent(folder);
		}
		folder.setText(location);

		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
		FileWriter fout = new FileWriter("/Program Files/Winamp Controller/Server Preferences.xml");
		outputter.output(properties, fout);
		fout.close();
	}

	public String readLoad() throws JDOMException, IOException {
		String location = "";
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build("/Program Files/Winamp Controller/Server Preferences.xml");

		Element properties = doc.getRootElement();
		if (properties != null) {
			Element previousLoaded = properties.getChild("PreviousLoaded");
			if (previousLoaded != null) {
				Element folder = previousLoaded.getChild("Folder");
				if (folder != null) {
					location = folder.getText();
				}
			}
		}
		return location;
	}

	/**
	 * Clears the playlist. Clears the list. Sets the song count.
	 */
	private void clear() {
		playlist.getSongs().clear();
		gui.listModel.clear();
		gui.statusLabel.setText(playlist.getSongCount() + "");
	}

	public void filter() {
		ArrayList<File> songs = playlist.getSongs();
		gui.listModel.clear();
		for (int i = 0; i < songs.size(); i++) {
			File file = songs.get(i);
			if (file.getAbsolutePath().toUpperCase().indexOf(gui.filterField.getText().toUpperCase()) > -1) {
				gui.listModel.addElement(file);
			}
		}
	}

	public void play(int index) {
		playlist.addSong(index);
	}

	public boolean play(String song) {
		boolean ret = true;
		int songNum = playlist.getSongNum(song);
		if (songNum > -1) {
			this.play(songNum);
		} else {
			ret = false;
		}
		return ret;
	}

	public void add() {
		int[] songs = gui.list.getSelectedIndices();
		File[] selectedSongs = new File[songs.length];
		ArrayList<File> loadedSongs = playlist.getSongs();

		for (int i = 0; i < songs.length; i++) {
			selectedSongs[i] = (File) gui.listModel.get(songs[i]);
		}
		for (int i = 0; i < selectedSongs.length; i++) {
			for (int j = 0; j < loadedSongs.size(); j++) {
				if (selectedSongs[i].equals(loadedSongs.get(j))) {
					playlist.addSong(j);
					break;
				}
			}
		}
	}

	public void previous() {
		playlist.prevSong();
	}

	public void playPause() {
		playlist.playPauseSong();
	}

	public void stop() {
		playlist.stopSong();
	}

	public void next() {
		playlist.nextSong();
	}

	@Override
	public void actionPerformed(ActionEvent command) {
		if (command.getActionCommand().equals("Browse")) {
			this.browse();
		} else if (command.getActionCommand().equals("Load")) {
			try {
				this.load();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (command.getActionCommand().equals("Clear")) {
			this.clear();
			PlaylistQueue.auto = false;
			LoadPanel.shuffle.setText("Shuffle: " + PlaylistQueue.auto);
		} else if (command.getActionCommand().equals("Filter")) {
			this.filter();
		} else if (command.getActionCommand().equals("Add to Playlist")) {
			this.add();
		} else if (command.getActionCommand().equals("<<")) {
			this.previous();
		} else if (command.getActionCommand().equals("||>")) {
			this.playPause();
		} else if (command.getActionCommand().equals("[]")) {
			this.stop();
		} else if (command.getActionCommand().equals(">>")) {
			this.next();
		} else if (command.getActionCommand().equals("Auto Shuffle")) {
			PlaylistQueue.auto = !PlaylistQueue.auto;
			LoadPanel.shuffle.setText("Shuffle: " + PlaylistQueue.auto);
		} else {
			System.err.println(command.getActionCommand());
		}
	}
}
